package com.bluemsun.naturallanguageprocessing.util;

import com.qianxinyao.analysis.jieba.keyword.TFIDFAnalyzer;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * @author :hucl
 * @describe :操作xlsx表的类
 */
public class OperateXlsxUtils {
    /**
     * 读取指定readPath的xlsx文件，并且将信息写到指定的writePath文件中去
     * @param readPath
     * @param writePath
     * @param id 问题id所在的位置
     * @param title 标题位置
     */
    public static void readXlsx(String readPath,String writePath,int id,int title) {
        BufferedWriter bufferedWriter = null;
        FileInputStream is = null;
        String str = null;
        TFIDFAnalyzer tfidfAnalyzer = null;
        try{
            bufferedWriter = new BufferedWriter(new FileWriter(writePath));
            // 读取的时候可以使用流，也可以直接使用文件名
            is =  new FileInputStream(readPath);
            Workbook xwb = new XSSFWorkbook(is);
            // 循环工作表sheet
            for(int numSheet = 0; numSheet < xwb.getNumberOfSheets(); numSheet++) {
                Sheet sheet = xwb.getSheetAt(numSheet);
                if(sheet == null) {
                    continue;
                }
                // 循环row，如果第一行是字段，则 numRow = 1
                for(int numRow = 1; numRow <= sheet.getLastRowNum(); numRow++) {
                    Row row = sheet.getRow(numRow);
                    if(row == null) {
                        continue;
                    }
                    tfidfAnalyzer = new TFIDFAnalyzer();
                    str = getValue(row.getCell(title));
                    str = str.replaceAll(" ","");
                    str = tfidfAnalyzer.analyze(str,str.length()).toString();
                    str = str.replaceAll(" ","");
                    str = str.substring(1,str.length()-1);
                    bufferedWriter.write(getValue(row.getCell(id))+" "+str+'\n');
                }
            }
        }catch(Exception e) {
            e.printStackTrace();
        }finally {
            try {
                bufferedWriter.flush();
                bufferedWriter.close();
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    private static String getValue(Cell cell) {
        String val = null;
        switch(cell.getCellType()) {
            case FORMULA:  //公式类型
                // 先计算表达式
                val = cell.getCellFormula();
                break;
            case BOOLEAN:  //布尔类型
                val = String.valueOf(cell.getBooleanCellValue());
                break;
            case STRING:   // 字符串类型
                val = cell.getStringCellValue().trim();
                break;
            case NUMERIC:  // 数值类型
                // 日期格式
                double numericCellValue = cell.getNumericCellValue();
                if(DateUtil.isCellDateFormatted(cell)) {
                    val = Date2Str(cell.getDateCellValue(), "yyyy-MM-dd HH:mm:ss");
                }else if(numericCellValue%1==0) {
                    val = String.valueOf((int)numericCellValue);
                } else{
                    // 四舍五入
                    val = new DecimalFormat("#.####").format(numericCellValue);
                }
                break;
            default: //其它类型
                break;
        }
        return val;
    }

    private static String Date2Str(Date date, String format){
        // Date -> LocalDateTime -> String
        DateTimeFormatter df = DateTimeFormatter.ofPattern(format);
        ZoneId zone = ZoneId.systemDefault();
        LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(),zone);
        return df.format(localDateTime);
    }
}
